package com.sphd.Restaurant.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sphd.Restaurant.R;
import com.sphd.Restaurant.base.BaseActivity;

import com.sphd.Restaurant.base.MyApplication;
import com.sphd.Restaurant.infos.LoginInfo;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.MyDataP;
import com.sphd.Restaurant.utils.AppManager;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.utils.FileUtil;
import com.sphd.Restaurant.utils.JsonUtil;
import com.sphd.Restaurant.utils.MultipartRequest;
import com.sphd.Restaurant.views.MyDataView;
import com.sphd.Restaurant.views.RoundImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class MyDataActivity extends BaseActivity implements MyDataView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_headportrait)
    RoundImageView ivHeadportrait;
    @BindView(R.id.layout_heard)
    LinearLayout layoutHeard;
    @BindView(R.id.et_mydata_name)
    EditText etMydataName;
    @BindView(R.id.layout_username)
    LinearLayout layoutUsername;
    @BindView(R.id.et_mydata_phone)
    TextView etMydataPhone;
    @BindView(R.id.layout_telNo)
    LinearLayout layoutTelNo;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.layout_sex)
    LinearLayout layoutSex;
    @BindView(R.id.my_birth)
    TextView myBirth;
    @BindView(R.id.layout_birthday)
    LinearLayout layoutBirthday;
    @BindView(R.id.my_self_info)
    EditText mySelfInfo;

    MyDataP myDataP;
    LoginInfo loginInfo;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;


    private PopupWindow popuWindow;//显示获取图片方式的popuwindows
    private View contentView;//底部的弹窗布局
    @BindView(R.id.content_my_data)
    LinearLayout parent;

    private Button btn_camera;//相机
    private Button btn_photo;//相册

    private static final int REQUE_CODE_CAMERA = 1;
    private static final int REQUE_CODE_PHOTO = 2;
    private static final int REQUE_CODE_CROP = 3;
    private File cameraFile; // 保存拍照后的图片文件
    Intent intent;
    String takePhotoPath;
    private String urlpath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_data);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> AppManager.getAppManager().finishActivity(this));
        btn_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File fileDir;
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    fileDir = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/user_photos");
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                } else {
                    Toast.makeText(MyDataActivity.this, "SD卡不在", Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
                takePhotoPath = fileDir.getAbsoluteFile() + "/" + System.currentTimeMillis() + ".png";
                cameraFile = new File(takePhotoPath);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(intent, REQUE_CODE_CAMERA);
                popuWindow.dismiss();
            }
        });
        btn_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, REQUE_CODE_PHOTO);
                popuWindow.dismiss();
            }
        });
    }

    private void initView() {
        intent = getIntent();
        setToolBar(toolbar, "个人信息", true);

        contentView = this.getLayoutInflater().inflate(R.layout.layout_takephoto, null);
        btn_camera = (Button) contentView.findViewById(R.id.camara);
        btn_photo = (Button) contentView.findViewById(R.id.photo);
        myDataP = new MyDataP(this);
        getMyMessage();

    }

    private void getMyMessage() {
        myDataP.addData(Model.HTTPURL + Model.MYDATA + "username=" + getString(Constants.USERPHONE));
    }

    @Override
    public void sendResInfo(LoginInfo loginInfo) {
        if (loginInfo != null) {
            this.loginInfo = loginInfo;
            etMydataName.setText(loginInfo.getUser_name());
            etMydataPhone.setText(loginInfo.getUser_phone());
            tvSex.setText(loginInfo.getUser_sex() == 1 ? "男" : "女");
            setImage(ivHeadportrait, loginInfo.getUser_photo());
            putString(Constants.USERNAME, TextUtils.isEmpty(loginInfo.getUser_name()) ? "未填写" : loginInfo.getUser_name());
            putString(Constants.USERPHOTO, loginInfo.getUser_photo());
        }
    }

    @OnClick({R.id.layout_heard, R.id.layout_sex, R.id.btn_finish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_heard:
                showPopuWindow();
                break;
            case R.id.layout_sex:
                showSex();
                break;
            case R.id.btn_finish:
                finishMySelf();
                break;
        }
    }

    private void finishMySelf() {
        if (TextUtils.isEmpty(etMydataName.getText().toString().trim())) {
            new SweetAlertDialog(MyDataActivity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("系统提示")
                    .setContentText("昵称为空确定保存吗?")
                    .setConfirmText("确定")
                    .setCancelText("取消")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            doUpload();
                        }
                    })
                    .showCancelButton(true)
                    .show();
        } else {
            doUpload();

        }
    }

    private void doUpload() {
        Map<String, String> map = new HashMap<>();
        map.put("username", getString(Constants.USERPHONE));
        map.put("name", TextUtils.isEmpty(etMydataName.getText().toString().trim()) ? "未填写" : etMydataName.getText().toString().trim());
        map.put("sex", tvSex.getText().toString().trim().equals("男") ? "1" : "0");

        Drawable drawable = ivHeadportrait.getDrawable();
        Bitmap bitmap = drawableToBitmap(drawable);
        urlpath = FileUtil.saveFile(context, "myheard.jpeg", bitmap);

        File f1 = new File(urlpath);
        if (!f1.exists()) {
            Toast.makeText(getApplicationContext(), "图片不存在，测试无效", Toast.LENGTH_SHORT).show();
            return;
        }
        List<File> files = new ArrayList<File>();
        files.add(f1);
        MultipartRequest request = new MultipartRequest(Model.HTTPURL + Model.UPDATEUSER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (JsonUtil.getJsonObject(response).getInteger("res") == 1) {
                    new SweetAlertDialog(MyDataActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("修改成功")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    getMyMessage();
                                }
                            }).show();
                } else {
                    showAlerDialog(1, "修改失败,请重试");

                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                showAlerDialog(1, "服务器连接错误，请稍后重试！");
            }
        }, "image", files, map); //注意这个key必须是f_file[],后面的[]不能少


        MyApplication.getRequestQueue().add(request);


    }

    /**
     * 显示PopupWindow用于选择图片上传方式
     */
    public void showPopuWindow() {
        if (null == popuWindow) {
            popuWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            popuWindow.setFocusable(true);
            popuWindow.setBackgroundDrawable(new BitmapDrawable());
            popuWindow.setAnimationStyle(R.style.popu_animation);
        }
        popuWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    private void showSex() {
        new AlertDialog.Builder(this).setTitle("请选择您的性别：").
                setIcon(R.mipmap.ic_launcher_small).
                setSingleChoiceItems(new String[]{"男", "女"},
                        loginInfo.getUser_sex() == 1 ? 0 : 1, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    tvSex.setText("男");
                                } else {
                                    tvSex.setText("女");
                                }
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", null).show();
    }

    @Override
    public void showdialog() {

    }

    @Override
    public void dissmissdialog() {

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUE_CODE_CAMERA:
                    startPhotoZoom(Uri.fromFile(cameraFile));
                    break;
                case REQUE_CODE_PHOTO:
                    if (null != data) {
                        startPhotoZoom(data.getData());
                    }
                    break;
                case REQUE_CODE_CROP:
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        // 取得SDCard图片路径做显示
                        // 取得SDCard图片路径做显示
                        Bitmap photo = extras.getParcelable("data");
                        Drawable drawable = new BitmapDrawable(null, photo);
                        ivHeadportrait.setImageDrawable(drawable);
                    }
                    break;
                default:
                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startPhotoZoom(Uri imageUri) {
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");// mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, REQUE_CODE_CROP);
    }

    /**
     * 将drawable转换为bitmap
     *
     * @param drawable
     * @return bitmap
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
}
